from flask import jsonify

from marshmallow import Schema
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from dao import db, ma


def json(msg: str = "", count=0, data=None, limit=10):
    """ 动态表格渲染响应 """
    res = {
        'msg': msg,
        'code': 0,
        'data': data,
        'count': count,
        'limit': limit

    }
    return jsonify(res)


def auto_model_jsonify(data, model: db.Model):
    """
    不需要建立schemas，直接使用orm的定义模型进行序列化
    基本功能，待完善
    示例
    power_data = curd.auto_model_jsonify(model=Dept, data=dept)
    """

    def get_model():
        return model

    class AutoSchema(SQLAlchemyAutoSchema):
        class Meta(Schema):
            model = get_model()
            include_fk = True
            include_relationships = True
            load_instance = True

    common_schema = AutoSchema(many=True)  # 用已继承ma.ModelSchema类的自定制类生成序列化类
    output = common_schema.dump(data)
    return output


def model_to_dicts(schema: ma.Schema, data, many=True):
    """
    :param schema: schema类
    :param model: sqlalchemy查询结果
    :param many: 如果序列化的单个的对象，那么就是False,如果是列表，那就是True
    :return: 返回单个查询结果
    """
    # 如果是分页器返回，需要传入model.items
    common_schema = schema(many=many)  # 用已继承ma.ModelSchema类的自定制类生成序列化类
    output = common_schema.dump(data)  # 生成可序列化对象
    return output
